package com.wzy.oa_sys.service.impl.file;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzy.oa_sys.mapper.file.OaFileMapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.file.OaFile;
import com.wzy.oa_sys.model.response.file.FileResp;
import com.wzy.oa_sys.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSClient ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Autowired
    private OaFileMapper oaFileMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public OaFile uploadFile(MultipartFile file, OaFile oaFile) {
        try {
            // 生成OSS文件路径
            String fileName = generateFileName(oaFile.getCFileName());

            // 上传到OSS
            ossClient.putObject(bucketName, fileName, file.getInputStream());

            // 设置文件路径
            oaFile.setCFilePath(fileName);

            // 保存文件信息到数据库
            // 这里需要你实现数据库保存逻辑
            saveToDatabase(oaFile);

            return oaFile;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Override
    public List<FileResp> fileList() {
        // 从数据库中获取文件列表
        List<OaFile> oaFiles = oaFileMapper.selectList(null);
        List<FileResp> fileRespList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");

        // 将 OaFile 转换为 FileResp
        List<FileResp> finalFileRespList = fileRespList;
        oaFiles.forEach(oaFile -> {
            finalFileRespList.add(FileResp.builder()
                    .nFileId(oaFile.getNFileId())
                    .cFileName(oaFile.getCFileName())
                    .nSize(df.format((double) oaFile.getNSize() / 1024) + "KB")
                    .dtUploadTime(oaFile.getDtUploadTime())
                    .nUserId(oaFile.getNUserId())
                    .cUserName(userMapper.selectUserById(oaFile.getNUserId()).getCRealName())
                    .build());
        });

        // 确保在这里执行排序，并将结果赋值回 fileRespList
        fileRespList = fileRespList.stream()
                .sorted(Comparator.comparing(FileResp::getDtUploadTime).reversed())
                .collect(Collectors.toList());
        // 可选：打印排序后的结果以进行验证
//        fileRespList.forEach(fileResp ->
//                System.out.println("Sorted Upload Time: " + fileResp.getDtUploadTime()));
        // 返回排序后的列表
        return fileRespList;
    }

    private String generateFileName(String originalFilename) {
        // 生成唯一的文件名，避免文件覆盖
        return UUID.randomUUID().toString() + "_" + originalFilename;
    }

    private void saveToDatabase(OaFile oaFile) {
        // 实现数据库保存逻辑
        // 需要你添加相应的Repository或Mapper来保存数据
        oaFileMapper.insert(oaFile);
    }

    @Override
    public OaFile getFileById(Long fileId) {

        return oaFileMapper.selectFileById(fileId);
    }

    @Override
    public OSSObject getOssFile(String filePath) {
        try {
            return ossClient.getObject(bucketName, filePath);
        } catch (OSSException e) {
            throw new RuntimeException("文件获取失败"+e.getMessage());
        }
    }

    @Override
    @Transactional
    public void deleteFile(Long fileId) throws Exception {
        // 1. 获取文件信息
        OaFile file = oaFileMapper.selectFileById(fileId);
        if (file == null) {
            throw new Exception("文件不存在");
        }

        try {
            // 2. 删除OSS中的文件
            if (file.getCFilePath() != null && !file.getCFilePath().isEmpty()) {
                // 从文件URL中提取OSS对象名
                String objectName = file.getCFilePath();
                ossClient.deleteObject(bucketName, objectName);
            }

            // 3. 删除数据库记录
            int result = oaFileMapper.deleteFileById(fileId);
            if (result != 1) {
                throw new Exception("数据库删除失败");
            }
        } catch (Exception e) {
            throw new Exception("文件删除失败：" + e.getMessage());
        }
    }

    @Override
    public List<FileResp> getThreeFiles() {
        List<FileResp> fileRespList = fileList();
        if (fileRespList.size() > 3) {
            fileRespList = fileRespList.subList(0, 3); // 保留前三个元素
        }
        return fileRespList;
    }
}
